package com.file.word;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author cxt
 * @date 2022/3/5
 * <p>
 * 根据word表格创建SQL语句
 */
@Slf4j
public class ReadWord {
    /**
     * 接收Word地址
     */
    public static String wordByPath(String path) {
        String buffer = "";
        FileInputStream inputStream = null;
        try {
            if (path.endsWith(".doc")) {
                inputStream = new FileInputStream(new File(path));
                WordExtractor word = new WordExtractor(inputStream);
                // String[] text = word.getCommentsText();// 评论
                // String[] endnoteText = word.getEndnoteText();// 尾注文本
                // String[] text = word.getFootnoteText();// 脚注文本
                // String[] text = word.getMainTextboxText();// 主文本框文本
                // String[] text = word.getParagraphText();// 段落,回车进行计算
                // System.out.println(Arrays.toString(text));
                buffer = word.getText(); // 里面的所有文字都会获取到
            } else if (path.endsWith(".docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                XWPFWordExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }

    /**
     * 使用MultipartFile 接收文件流
     *
     * @param file
     * @throws IOException
     */
    public void importWord(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        String content = "";
        if (fileName.endsWith("docx")) {
            XWPFDocument xdoc = new XWPFDocument(inputStream);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            content = extractor.getText();
            System.out.println(content);
            extractor.close();
        } else if (fileName.endsWith(".doc")) {
            WordExtractor ex = new WordExtractor(inputStream);
            content = ex.getText();
            System.out.println(content);
            ex.close();
        } else {
            throw new IOException("此文件不是word文档");
        }
    }

    /**
     * 创建建表语句
     */
    public StringBuilder createTable(String path) {
        StringBuilder result = new StringBuilder(); // 结果
        String s = wordByPath(path); // 读取word文件
        String[] split = s.split("\n");

        String name = "";
        String remarks = "";
        String[] content = new String[split.length];
        int j = 0;
        for (int i = 0; i < split.length; i++) {
            String s1 = split[i];
            if (!s1.isEmpty()) {
                String[] line = s1.split(" ");
                if (line.length == 1) {
                    line = s1.split("\t");
                }
                if (line.length == 2) {
                    if ("id".equals(line[0])) {
                        // 这一行是id列
                        content[j++] = "`id` " + line[1] + " NOT NULL AUTO_INCREMENT";
                    } else {
                        name = line[1];
                        remarks = line[0];
                    }
                } else if (line.length > 2) {
                    // 正常的内容
                    content[j++] = "`" + line[0] + "` " + line[1] + " COMMENT '" + line[2] + "'";

                    // 判断是否是最后一个表
                    if (i == split.length - 1) {
                        MyTable myTable = new MyTable(name, remarks, content);
                        String table = myTable.createTable();
                        result.append("\n");
                        result.append(table);
                    }
                }
            } else {
                // 表示一个表创建完成
                if (name.isEmpty() && remarks.isEmpty()) {
                    continue;
                }
                MyTable myTable = new MyTable(name, remarks, content);
                String table = myTable.createTable();
                if (result.length() != 0) result.append("\n");
                result.append(table);

                // 在完成一个表的创建之后初始化参数
                name = "";
                remarks = "";
                content = new String[split.length];
                j = 0;
            }
        }
        return result;
    }

    @Data
    @AllArgsConstructor
    class MyTable {
        private String name;
        private String remarks;
        private String[] content;

        /**
         * 创建表
         */
        public String createTable() {
            String start = "CREATE TABLE `" + this.name + "` (";

            String[] array = Arrays.stream(content).filter(Objects::nonNull).toArray(String[]::new);
            String join = StringUtils.join(array, ",");

            String end = "  `create_time` datetime NOT NULL COMMENT '创建时间',\n" + "  `create_by` varchar(32) NOT NULL COMMENT '创建人',\n" + "  `update_time` datetime DEFAULT NULL COMMENT '更新时间',\n" + "  `update_by` varchar(32) DEFAULT NULL COMMENT '更新人',\n" + "  PRIMARY KEY (`id`)" + ") ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='" + this.remarks + "';";
            return start + join + end;
        }
    }

    @Test
    public void test() {
        StringBuilder table = createTable("src/main/resources/json/病历表.docx");
        // 打印结果
        System.out.println(table);
    }

}
